import re

from fastapi import APIRouter
from re_common.baselibrary.tools.myparsel import MParsel
from re_common.baselibrary.utils.basedict import BaseDicts
from re_common.baselibrary.utils.core.mlamada import bools_string
from re_common.vip.baseencodeid import BaseLngid

from apps.allsubdb.paper_beijingribao.models import BjrbParseHtmlModel, PaperBeiJingRiBaoParseStepFour
from apps.core.callback import default_call_back
from apps.core.m_route import ContextIncludedRoute
from apps.core.return_info import InputInfoModel, ReturnInfo

router = APIRouter(route_class=ContextIncludedRoute)


@router.post("/step1/parse_journal_id")
async def parse_article(input: InputInfoModel[BjrbParseHtmlModel]):
    """
    解析信息用于下载ref rel等
    :param input:
    :return:
    """
    return_info = ReturnInfo()
    html = input.data.html
    periodDate = input.data.periodDate
    css_dicts = {

        'bzinfo': {
            'parent': '.nav-panel-primary',  # 解析主体
            'children': {
                'parent': '.nav-items',
                'children': {
                    'versions_title': '.nav-panel-heading::text',  # 版面名称
                    'parent': '.nav-list-group li',  # 单版面节点
                    'children': {
                        'title': 'a::text',  # 每版的文章名称
                        'url': 'a::attr(data-href)',  # 每版文章url
                    }
                }
            }
        }
    }

    rule = re.compile(r"第[0-9]*版")
    mc = MParsel(html=html)
    new_dict = mc.css_parsel(sel=mc.sel, css_selector=css_dicts)


    BaseDicts.get_recursive_dict(new_dict, None, default_call_back)

    for dic_list in new_dict["bzinfo"]["children"]: # 最外层字典的列表的元素
        for dic_1 in dic_list["children"]:

            banmiantitle = dic_1["versions_title"]
            versions_title_forward = rule.sub("", banmiantitle).strip()
            page = rule.findall(banmiantitle)[0].replace("第", '').replace("版", '')
            versions_title = "({})".format(page.zfill(2)) + versions_title_forward
            # 处理版面title
            dic_1["versions_title"] = versions_title
            dic_1["days"] = periodDate
            cid = periodDate + "page" + str(int(page))
            dic_1["cid"] = cid
            dic_1["page"] = page
            dic_1["versions_url"] = "https://bjrbdzb.bjd.com.cn/bjrb/mobile/{}/{}/{}_m.html#page{}".format(periodDate[0:4],periodDate,periodDate,str(int(page)-1))
            dic_1["jsondicts"] = {}
            # dic_1["jsondicts"]["count"] = len(dic_1["children"])
            for one_dic in dic_1["children"]:
                one_dic_url = one_dic["url"]
                one_dic["url"] = "https://bjrbdzb.bjd.com.cn/bjrb/mobile/{}/{}".format(periodDate[0:4], periodDate) + one_dic_url.strip('.')
            for index, value in enumerate(dic_1["children"]):
                dic_1["jsondicts"][str(index+1)] = value
            dic_1.pop("children")



    return_info.status = bools_string(True)
    return_info.msg_code = 200
    return_info.msg = ""
    return_info.data = new_dict["bzinfo"]["children"][0]
    return return_info.todict()


@router.post("/step4/parse_article")
async def parse_article_one(input: InputInfoModel[PaperBeiJingRiBaoParseStepFour]):
    """
    解析信息用于下载ref rel等
    :param input:
    :return:
    """
    return_info = ReturnInfo()
    html = input.data.html
    getdicts = input.data.jsondicts
    downdate = input.data.downdate
    rawid = input.data.rawid
    batch = input.data.batch
    css_dicts = {
        'bzinfo': {
            'parent': '#main',  # 解析主体
            'children': {
                "title_catalyst": '#guide::text',
                "title": '#main-title b::text',
                "title_alt": '#sub-title::text',
                "authors": ".article-count-info div::text",
                'parent': '#content p',  # 正文
                'children': {
                    'p_info': 'p *::text',  # 版面名称

                    }
                }
            }
        }

    results_list = list()
    mc = MParsel(html=html)
    new_dict = mc.css_parsel(sel=mc.sel, css_selector=css_dicts)

    BaseDicts.get_recursive_dict(new_dict, None, default_call_back)
    dic_list =new_dict["bzinfo"]["children"][0]
    for p_info in dic_list["children"]:
        results_list.append(p_info["p_info"])
    dic_list["abstract"] = "\n".join(results_list)
    dic_list.pop("children")

    dic = {
        "lngid": BaseLngid().GetLngid("00352", rawid),
        "sub_db_id": "00352",
        "batch": batch,
        "rawid": rawid,
        "source_type": '11',
        "journal_name": "北京日报",
        'provider_url': getdicts["url"],
        'title': dic_list["title"],
        'title_catalyst': dic_list["title_catalyst"],
        'title_alt': dic_list["title_alt"],
        "author": dic_list["authors"],
        "abstract": dic_list["abstract"],
        'pub_year': getdicts["years"],
        'pub_date': getdicts["days"],
        'meeting_counts': getdicts["page"],
        'index': getdicts["index"],
        "sub_db": 'PAPER',
        "zt_provider": 'bjrbpaper',
        "provider": 'BJD',
        "product": 'BJRBDZB',
        "country": "CN",
        "language": "ZH",
        "web_site": "https://www.bjd.com.cn/",
        'down_date': downdate
    }



    return_info.status = bools_string(True)
    return_info.msg_code = 200
    return_info.msg = ""
    return_info.data = {"result": dic}
    return return_info.todict()


